import React from 'react';
import { connect } from 'react-redux';
import BaseComponent from '../../components/common/baseComponent.js';
import { getQueryParam } from '../../utils/url';
import { copy, loadScript } from '../../utils/func';
import toast from '../../utils/toast';

@connect(() => {
  return {};
})
class PreviewInvoice extends BaseComponent {
  componentDidMount() {
    if (!window.pdfjsLib) {
      loadScript('/lib/pdfjs/pdf.min.js', this.renderPdf);
    } else {
      this.renderPdf();
    }
  }

  renderPdf = () => {
    const url = getQueryParam('url');
    window.pdfjsLib.GlobalWorkerOptions.workerSrc = '/lib/pdfjs/pdf.worker.min.js';
    //
    // Asynchronous download PDF
    //
    const loadingTask = window.pdfjsLib.getDocument({
      url,
      cMapUrl: '/lib/pdfjs/cmaps/',
      cMapPacked: true,
    });
    loadingTask.promise.then((pdf) => {
      // Fetch the first page
      //
      pdf.getPage(1).then((page) => {
        const scale = 1.5;
        const viewport = page.getViewport({ scale });
        //
        // Prepare canvas using PDF page dimensions
        //
        const canvas = document.getElementById('pdf');
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        //
        // Render PDF page into canvas context
        //
        const renderContext = {
          canvasContext: context,
          viewport,
        };
        page.render(renderContext);
      });
    });
  }

  clickCopy = () => {
    const url = getQueryParam('url');
    copy(url, () => toast('复制成功'));
  }
  render() {
    return (
      <div className="invoice-preview">
        <canvas className="pdf" id="pdf" />
        <div className="save-btn" onClick={this.clickCopy}>复制发票链接</div>
      </div>
    );
  }
}

export default PreviewInvoice;
